package org.farm2.base.event;

import lombok.extern.slf4j.Slf4j;
import org.farm2.base.event.face.Farm2Events;
import org.farm2.base.event.inter.Farm2EventHandle;
import org.farm2.tools.files.Farm2ProcessState;
import org.farm2.tools.i18n.I18n;

import java.util.List;

/**
 * 运行事件处理器
 */
@Slf4j
public class Farm2EventRunner {
    private static Boolean isRun = false;

    synchronized
    public static void runHandles() {
        if (isRun) {
            return;
        }
        isRun = true;
        new Thread() {
            public void run() {
                try {
                    Farm2ProcessState.sleep(2000);

                    for (int n = 0; n < 100; n++) {

                        List<F2Event> events = Farm2Events.getEvent(10);
                        if (events.size() > 0) {
                            for (F2Event event : events) {
                                for (Farm2EventHandle handle : Farm2Events.getHandles()) {
                                    try {

                                        handle.handle(event);
                                    } catch (Exception e) {
                                        log.error(I18n.msg("处理事件:?", event), e);
                                    }
                                }
                            }
                        } else {

                            break;
                        }
                    }
                } finally {
                    isRun = false;
                }
            }
        }.start();
    }
}
